package com.zghhost.codedemo.sshclient;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.zghhost.codedemo.util.IOUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.concurrent.*;

/**
 * @author guohua.zhang@zhaopin.com.cn
 * @Date 2019/4/1 16:41
 */
public class PortScanWithNmap {

    public static File file = new File("/Users/wow/Desktop/zhaopin_port_scan.txt");
    public static BufferedWriter bw;


    public static void main(String[] args)throws Exception{
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
//        print(testnmap("172.20.10.0/24"));
        nmapHostGroup("39.96.126");
    }

    public static String testnmap(String hostname)throws Exception{
        Process process = Runtime.getRuntime().exec("nmap "+hostname);//扫描全部端口可以加" -p1-65535"
        return IOUtil.is2str(process.getInputStream(),true);
    }

    public static void nmapHostGroup(String ipduan)throws Exception{
        int nThreads = 20;
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d").build();
        ExecutorService executor = new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        for(int i=1,ic=254;i<ic;i++){
            final int currentInd = i;
            executor.execute(() -> {
                try{
                    String msg = testnmap(ipduan+"."+currentInd);
                    PortScanWithNmap.print(msg);
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
        }

        executor.shutdown();
    }

    static int x=0;
    synchronized private static void print(String msg)throws Exception{
        if(msg.indexOf("Host seems down") == -1){
            bw.write("----------------------------------------------split line----------------------------------------------\n");
            bw.write(msg.replaceAll(".* closed .*\n\r","")+"\n");
            bw.write("----------------------------------------------split line----------------------------------------------\n");
            bw.flush();

            System.out.println("----------------------------------------------split line----------------------------------------------");
            System.out.println(msg.replaceAll(".* closed .*\n\r",""));
            System.out.println("----------------------------------------------split line----------------------------------------------");
        }
    }
}
